package cn.kbyue.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @author XL
 * @version 0.1
 * @date 2021/7/25 17:24
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 内存模式用户
     */
    @Bean
    UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("admin")
                .password(passwordEncoder().encode("123456"))
                .authorities("product-api")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    /**
     * 指定客户端登录信息来源
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 从内存中取数据
        clients.inMemory()
                .withClient("baidu")
                .secret(passwordEncoder().encode("123456"))
                // 对应 数据中的 resource_ids
                .resourceIds("product_api")
                .authorizedGrantTypes(
                        "authorization_code",
                        "password",
                        "client_credentials",
                        "implicit",
                        "refresh_token"
                )
                .scopes("read", "write")
                // 不自动同意授权资源，需要手动授权
                .autoApprove(false)
                // 验证回调地址
                .redirectUris("http://www.baidu.com")
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }

    /**
     * 授权码模式专用对象
     * 可选模式：
     *   - JdbcAuthorizationCodeServices    - table: oauth_code
     *   - InMemoryAuthorizationCodeServices
     *   - RandomValueAuthorizationCodeServices
     */
    // @Bean
    // public AuthorizationCodeServices authorizationCodeServices() {
    //     return new InMemoryAuthorizationCodeServices();
    // }

    /**
     * token保存策略
     * 可选策略：
     *   - InMemoryTokenStore
     *   - JdbcTokenStore    - table: oauth_access_token, oauth_refresh_token
     *   - JwkTokenStore
     *   - JwtTokenStore
     *   - RedisTokenStore
     */
    // @Bean
    // public TokenStore tokenStore() {
    //     return new InMemoryTokenStore();
    // }

    /**
     * 授权信息保存策略
     * 可选策略:
     *   - InMemoryApprovalStore
     *   - JdbcApprovalStore    - table: oauth_approvals
     *   - TokenApprovalStore
     */
    // @Bean
    // public ApprovalStore approvalStore() {
    //     return new InMemoryApprovalStore();
    // }

    /**
     * OAuth2的主配置信息
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // .tokenStore(tokenStore())
                // .approvalStore(approvalStore())
                // .authorizationCodeServices(authorizationCodeServices())
                // 支持 password 模式
                .authenticationManager(authenticationManager)
                // 允许请求方式 GET, POST
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    /**
     * 检测 token 的安全策略
     * 其中的 配置项也可通过配置文件设置
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 允许form表单客户端认证,允许客户端使用client_id和client_secret获取token
                .allowFormAuthenticationForClients()
                // 通过验证返回token信息, 正式使用可以调为 "isAuthenticated()"
                // 配置文件配置： security.oauth2.authorization.check-token-access
                .checkTokenAccess("permitAll()")
                // 获取token请求不进行拦截
                .tokenKeyAccess("permitAll()")
                .passwordEncoder(passwordEncoder());
    }

}
